package me.illtamer.infinite.file.loader;

import lombok.extern.slf4j.Slf4j;
import me.illtamer.infinite.Translate;
import me.illtamer.infinite.factory.SingletonFactory;
import me.illtamer.infinite.file.FileType;
import me.illtamer.infinite.file.parser.TypeParser;
import me.illtamer.infinite.file.source.FileSource;
import me.illtamer.infinite.hook.TranslateHook;
import me.illtamer.infinite.hook.TranslatorAdaptor;
import me.illtamer.infinite.pojo.Global;
import org.bukkit.configuration.ConfigurationSection;

import java.util.HashMap;

/**
 * 文件调度类
 * */
@Slf4j
class DispatchFileParserHandler {

    static final HashMap<FileType, TypeParser> PARSER_MAP = new HashMap<>();

    private boolean init = false;

    /**
     * 依据注册的处理器调度文件源
     * @return 是否成功处理
     * */
    public boolean handle(FileSource source) {
        TypeParser parser = null;
        try {
            ConfigurationSection api = Translate.CONFIG.getSection("api-manager");

            Global global = SingletonFactory.getSingleton(Global.class);
            TranslatorAdaptor adaptor = TranslateHook.getGlobalAdaptor(global);
            if (!init)
                init = adaptor.init(global, api);

            parser = (parser = PARSER_MAP.get(source.getType())) == null ? PARSER_MAP.get(FileType.ALL) : parser;
            if (parser == null) {
                log.warn("Unregistered {} parser, this source({}) will be skipped !", source.getType(), source);
                return false;
            }
            parser.parse(adaptor, source);
            return true;
        } catch (Exception e) {
            log.error("Unexpected error when parser({}) handler source({})", parser, source, e);
        }
        return false;
    }

}
